<template>
  <div :class="$style.page">
    <top-title :name="$t('title')" :height="200" color="#ffffff" :size="35" :mouse-radius="50" />

    <div :class="$style.language" v-if="appStore.i18n">
      <el-dropdown>
        <el-space>
          <svg-icon name="yuyan"></svg-icon>
          <span>{{ language }}</span>
          <svg-icon name="xiala"></svg-icon>
        </el-space>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              v-for="item in langs"
              :key="item.key"
              :disabled="item.key == locale"
              @click="changeLanguage(item)"
              >{{ item.title }}</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <div :class="$style.panel" class="flex flex-ac">
      <div :class="$style.left" class="f-x">
        <img :src="loginBg" alt="" />
      </div>

      <div :class="$style.right" ref="loadingRef">
        <div :class="$style.form">
          <div :class="$style.bg"></div>
          <h1 :class="$style.title">
            <span>{{ $t('tip') }}</span>
          </h1>

          <el-form class="form" ref="loginRef" :model="loginForm" :rules="loginRules">
            <el-form-item prop="username" key="username">
              <el-input
                v-focus
                clearable
                v-model="loginForm.username"
                :placeholder="$t('account')"
                tabindex="1"
                size="large"
                :prefix-icon="User"
                @keyup.enter="handleSubmitLogin"
              >
              </el-input>
            </el-form-item>

            <el-form-item prop="password" key="password">
              <el-tooltip
                :visible="capsTooltip"
                :content="$t('caps_lock')"
                placement="right"
                manual
              >
                <el-input
                  clearable
                  :placeholder="$t('password')"
                  tabindex="2"
                  v-model="loginForm.password"
                  type="password"
                  show-password
                  size="large"
                  :prefix-icon="Lock"
                  @keyup="checkCapslock"
                  @blur="capsTooltip = false"
                >
                </el-input>
              </el-tooltip>
            </el-form-item>

            <el-form-item prop="code" key="code">
              <el-input
                v-model="loginForm.code"
                clearable
                :placeholder="$t('code')"
                maxlength="6"
                tabindex="3"
                size="large"
                :prefix-icon="Key"
                @keyup.enter="handleSubmitLogin"
              >
              </el-input>
            </el-form-item>

            <div :class="$style.btns">
              <div :class="$style.btn" @click="handleSubmitLogin">{{ $t('login') }}</div>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { User, Lock, Key } from '@element-plus/icons-vue'
import { useAppStore, useUserStore } from '@/stores'
import { request } from '@/api'
import topTitle from './title.vue'
import { langs } from '@/locales'
import type { Lang } from '@/locales/type'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const $t = (text: string = '', params: AnyObject = {}) => {
  return t(`login_page.${text}`, params)
}

//	指令 v-focus
const vFocus = {
  mounted: (el: HTMLElement) => {
    // 聚焦元素
    el.querySelector('input')?.focus()
  }
}

const userStore = useUserStore()
const appStore = useAppStore()

const locale = computed(() => appStore.language)
const language = computed(() => langs.find(item => item.key === locale.value)?.title)

const changeLanguage = (e: Lang) => {
  appStore.updateLangeuage(e.key)
}

// 登录背景
const loginBg = new URL('/imgs/login-icon.png', import.meta.url).href

const env = import.meta.env
let isDev = env.VITE_MODE == 'dev'

type loginForm = {
  username: string
  password: string
  code: string
  randomStr: string
}

const loginForm = reactive<
  Parameters<typeof request.login>[0] & {
    code: string
  }
>({
  username: isDev ? 'test' : '',
  password: isDev ? '123456' : '',
  code: isDev ? '1' : ''
})

const loginRules = reactive({
  username: [{ required: true, message: () => $t('rules.account'), trigger: 'blur' }],
  password: [{ required: true, message: () => $t('rules.password'), trigger: 'blur' }],
  code: [
    {
      required: true,
      validator: (_rule: any, value: String, callback: Function) => {
        !value && (value = '')
        if (value == '') {
          callback(new Error($t('rules.code')))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 大小写提示
const capsTooltip = ref(false)
// 重定向地址
const redirect = ref<any>('')
// 路由参数
const otherQuery = ref({})

// 登录
const loginRef = ref()
const loadingRef = ref()

const route = useRoute()
const router = useRouter()

// 获取路由参数除重定向字段
const getOtherQuery = (query: any) => {
  return Object.keys(query).reduce((acc: any, cur: string) => {
    if (cur !== 'redirect') {
      acc[cur] = query[cur]
    }
    return acc
  }, {})
}

// 监听
watch(
  route,
  ({ query }) => {
    if (query) {
      redirect.value = query.redirect != 'error' ? query.redirect || '' : ''
      otherQuery.value = getOtherQuery(query)
    }
  },
  { immediate: true }
)

// 登录
const handleSubmitLogin = () => {
  const loginInstance: any = loginRef.value
  if (!loginInstance) return

  loginInstance.validate((valid: any) => {
    if (!valid) return

    userStore.login(loginForm, loadingRef.value).then(_ => {
      const hostname = location.hostname
      const domian = hostname.split('.').slice(-3).join('.') //根域名
      if (redirect.value.indexOf(domian) < 0) {
        router.push({ path: redirect.value || '/', query: otherQuery.value })
      } else {
        // 跳转地址
        window.location.href = decodeURIComponent(redirect.value)
      }
    })
  })
}

// 检测键盘是否开启大写
const checkCapslock = ({ shiftKey, key, keyCode }: any = {}) => {
  if (keyCode == 13) {
    handleSubmitLogin()
    return
  }
  if (key && key.length === 1) {
    if ((shiftKey && key >= 'a' && key <= 'z') || (!shiftKey && key >= 'A' && key <= 'Z')) {
      capsTooltip.value = true
    } else {
      capsTooltip.value = false
    }
  }
  if (key === 'CapsLock' && capsTooltip.value === true) {
    capsTooltip.value = false
  }
}
</script>

<style lang="scss" module>
@use './style.scss';
</style>
